package com.dh.convert.rule.function;

import java.math.BigDecimal;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.util.TypeUtils;
import com.googlecode.aviator.runtime.function.AbstractFunction;
import com.googlecode.aviator.runtime.function.FunctionUtils;
import com.googlecode.aviator.runtime.type.AviatorBoolean;
import com.googlecode.aviator.runtime.type.AviatorObject;

/**
 * 
 * 类AmountCheckFunction.java的实现描述：金额校验
 * @author chenwenjing001 2018年11月14日 下午3:34:06
 */
public class AmountCheckFunction extends AbstractFunction {
	@Override
	public String getName() {
		return "amountCheck";
	}

	/**
	 * 精度校验
	 */
	@Override
	public AviatorBoolean call(Map<String, Object> env, AviatorObject arg, AviatorObject arg1) {
		return call(env,arg,arg1,null,null);
	}
	
	@Override
	public AviatorBoolean call(Map<String, Object> env, AviatorObject arg, AviatorObject arg1, AviatorObject arg2) { 
		Object o = arg1.getValue(env);
		//大小金额判断（不含精度）
		if(o instanceof String){
			return call(env,arg,null,arg1,arg2);
		}
		//精度及最小金额判断
		return call(env,arg,arg1,arg2,null);
	}

	@Override
	public AviatorBoolean call(Map<String, Object> env, AviatorObject arg, AviatorObject arg1, AviatorObject arg2,AviatorObject arg3) {
		if(null == arg){
			return AviatorBoolean.TRUE;
		}
		try {
			String amount = TypeUtils.castToString(arg.getValue(env));
			if (StringUtils.isBlank(amount)) {
				return AviatorBoolean.TRUE;
			}
			BigDecimal v = new BigDecimal(amount);
			if(null!=arg1){
				Long scale = (Long) FunctionUtils.getNumberValue(arg1, env);
				if (null!=scale && v.scale() != scale) {
					return AviatorBoolean.FALSE;
				}
			}
			
			if(null!=arg2){
				String min = FunctionUtils.getStringValue(arg2, env);
				if (min != null && v.compareTo(new BigDecimal(min)) < 0) {
					return AviatorBoolean.FALSE;
				}
			}
			
			if(null!=arg3){
				String max = FunctionUtils.getStringValue(arg3, env);
				if (max != null && v.compareTo(new BigDecimal(max)) > 0) {
					return AviatorBoolean.FALSE;
				}
			}
		} catch (Exception e) {
			return AviatorBoolean.FALSE;
		}
		return AviatorBoolean.TRUE;
	}

}
